package com.webchat.aigc.llm;


import com.webchat.common.constants.ConnectConstants;
import com.webchat.common.enums.AiFunctionEnum;
import com.webchat.common.enums.ChatMessageTypeEnum;
import com.webchat.common.enums.PromptTemplateEnum;
import com.webchat.common.enums.messagequeue.MessageQueueEnum;
import com.webchat.common.helper.SessionHelper;
import com.webchat.common.helper.SseEmitterHelper;
import com.webchat.common.service.messagequeue.producer.MessageQueueProducer;
import com.webchat.common.util.JsonUtil;
import com.webchat.domain.vo.llm.FunctionCallResponse;
import com.webchat.domain.vo.llm.image.ImageGenerateResponse;
import com.webchat.domain.vo.llm.image.RequestGenerateBaseParam;
import com.webchat.domain.vo.llm.image.RequestGenerateParam;
import com.webchat.domain.vo.request.mess.ChatMessageRequestVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class AiAgentFlowService {

    @Autowired
    private GPTChatService gptChatService;
    @Autowired
    private AiFunctionCallService aiFunctionCallService;
    @Autowired
    private AiGenImageService aiGenImageService;

    @Autowired
    private MessageQueueProducer<ChatMessageRequestVO, Long> messageQueueProducer;

    private String getSSEBizCode() {
        return ConnectConstants.ConnectBiz.getBizCode(ConnectConstants.ClientEnum.PC,
                                                      ConnectConstants.AppEnum.WEB,
                                                      ConnectConstants.BizEnum.CHAT);
    }

    /**
     * 机器人问答Agent服务
     * 1、意图识别
     * 2、文生文（kimi/deepseek） / 文生图（LibLib模型）
     *
     * @param message
     */
    public void doAgent(String message) {

        ChatMessageRequestVO chatMessage = JsonUtil.fromJson(message, ChatMessageRequestVO.class);

        if (!SseEmitterHelper.isExist(getSSEBizCode(), chatMessage.getSenderId())) {
            /**
             * 因为当前doAgent AIGC服务消费来自webchat-connect服务的websocket端点的MQ广播消息
             * 所以，在分布式部署场景下，可能当前消息发送人的sse链接并不在当前节点。
             */
            return;
        }

        /**
         * 消息持久化用户发给机器人消息
         */
        this.persistentAiMessage(chatMessage.getSenderId(), chatMessage.getReceiverId(), chatMessage.getMessage());

        String senderId = chatMessage.getSenderId();
        /**
         * 1. 意图识别
         */
        SseEmitterHelper.send(this.getSSEBizCode(), senderId, "意图识别中...");
        FunctionCallResponse functionCallResponse;
        try {

            Map<String, Object> vars = new HashMap<>();
            vars.put("input", chatMessage.getMessage());
            functionCallResponse =
                    aiFunctionCallService.getFunction(vars, PromptTemplateEnum.ROBOT_FC);
            log.info("意图识别结果 =====> input: {}, response:{}",
                    chatMessage.getMessage(), JsonUtil.toJsonString(functionCallResponse));
            String functionInfo = "意图识别："+ AiFunctionEnum.getFunctionName(functionCallResponse.getFunction());
            SseEmitterHelper.send(this.getSSEBizCode(), senderId, functionInfo);
        } catch (Exception e) {
            log.error("意图识别异常 =====> input: {}", chatMessage.getMessage(), e);
            SseEmitterHelper.send(this.getSSEBizCode(), senderId, "意图识别失败，稍后重试～");
            return;
        }
        String aiInput = functionCallResponse.getPrompt();
        /**
         * 2. 根据意图执行对应工作流
         */
        SseEmitter sseEmitter = SseEmitterHelper.get(this.getSSEBizCode(), senderId);
        String agentResponse = null;
        if (AiFunctionEnum.CHAT.name().equals(functionCallResponse.getFunction())) {
            // 机器人对话
            agentResponse = gptChatService.chat(sseEmitter, chatMessage);
        } else if (AiFunctionEnum.IMAGE.name().equals(functionCallResponse.getFunction())) {
            aiGenImageService.doGenerate(aiInput, this.getSSEBizCode(),senderId);
        }

        /**
         * 机器人响应消息持久化
         */
        if (agentResponse != null) {
            this.persistentAiMessage(chatMessage.getReceiverId(), chatMessage.getSenderId(), agentResponse);
        }
    }


    /**
     * 机器人对话场景，消息持久化
     *
     * @param senderId
     * @param receiverId
     * @param message
     */
    private void persistentAiMessage(String senderId, String receiverId, String message) {
        ChatMessageRequestVO chatMessageRequestVO = new ChatMessageRequestVO();
        chatMessageRequestVO.setSenderId(senderId);
        chatMessageRequestVO.setReceiverId(receiverId);
        chatMessageRequestVO.setMessage(message);
        chatMessageRequestVO.setType(ChatMessageTypeEnum.CHAT_TEXT.getType());
        messageQueueProducer.send(MessageQueueEnum.QUEUE_PERSISTENT_MESSAGE, chatMessageRequestVO);
    }
}
